import pandas as pd
from mlxtend.preprocessing import TranspactionEncoder
from mlxtend.frequent_patterns import apriori,association_rules

df=pd.read_excel('data-mining\asscociationRules\餐厅数据.xlsx')
print(df.head)

trsations=df['菜品'].str.split(',').to_list()

te = TransactionEncoder()
te_ary=te.fit(trsations).transform(trsations)
de_enecoded=pd.DataFrame(te_ary,columns=te.columns_)

#print(de_enecoded.head)
frequent_itemsets=apriori(de_enecoded,min_support=0.1,use_colnames=True)
frequent_itemsets.sort_values(by='support',ascending=False,inplace=True)

print(frequent_itemsets[frequent_itemsets.itemsets.apply(lambda x: len(x) ==2)])

rules=association_rules(frequent_itemsets,metric="confidence",min_threshold=0.1)

effective=rules[rules(rules['lift']>1)&(rules['confidence']>0.1)
].sort_values(by=['lift','confidence'],asending=False)

#print(effective[["antecedents","consequents","support","confidence","lift"]])

import matplotlib.pyplot as plt
import networkx as nx

plt.rcParams['font.sans-serif']=['SimHer']
plt.rcParams['axes-unicode_minus']=False

G=nx.DiGraph()

for _,row in effective.iterrows():
    G.add_edge(','.join(list(row['antecedents'])),
               ','.oin(list(row['consequents'])),
               weight=row['lift'])
    
plt.figure(figsize=(12,8))
pos=nx.spring_layout(G)
nx.draw(G,pos,
        with_labels=True,
        edge_color=[G[u][v]['weight'] for u,v in G.edges()],
        width=2.0,
        edege_cmap=plt.cm.Blues)



